package cn.sciento.export.endpoint;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.Future;

import cn.sciento.core.async.AsyncTaskState;
import cn.sciento.export.ExportFutureManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.util.Assert;

@Endpoint(id = "async-export-endpoint")
public class AsyncExportEndpoint {
    private static final String NOT_FOUND = "404";

    private static final String SUCCESS = "success";

    private static final String FAILED = "failed";

    @Autowired
    private ExportFutureManager futureManager;

    @ReadOperation
    public List<String> getExportTaskIds() {
        return (this.futureManager == null) ? null : this.futureManager.getAllKeys();
    }

    @ReadOperation
    public String getExportTaskState(@Selector String uuid) {
        Assert.notNull(uuid, "UUID must not be empty");
        Future future;
        if (this.futureManager == null || (future = this.futureManager.get(UUID.fromString(uuid))) == null)
            return "404";
        if (future.isDone())
            return AsyncTaskState.DONE.getCode();
        if (future.isCancelled())
            return AsyncTaskState.CANCELLED.getCode();
        return AsyncTaskState.DOING.getCode();
    }

    @WriteOperation
    public String cancelExportTask(@Selector String uuid) {
        Assert.notNull(uuid, "UUID must not be empty");
        if (this.futureManager != null)
            return this.futureManager.cancel(uuid) ? "success" : "failed";
        return "failed";
    }
}
